package com.dtborad.myblog.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dtborad.myblog.common.CommonErrorCode;
import com.dtborad.myblog.common.Result;
import com.dtborad.myblog.entity.Categories;
import com.dtborad.myblog.entity.Posts;
import com.dtborad.myblog.service.CategoryService;
import com.dtborad.myblog.service.PostService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/category")
@Slf4j
@Api(tags = "分类模块")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private PostService postService;

    @GetMapping("/list")
    public Result<Map<String, Object>> getCategoriesList(@RequestParam(defaultValue = "1") int pagenum,
                                                      @RequestParam(defaultValue = "5") int pagesize,
                                                      @RequestParam(defaultValue = "") Integer categoryid,
                                                      @RequestParam(defaultValue = "") String categoryname) {
        Page<Categories> currentPage = categoryService.getAllCategoryByPageSize(pagenum, pagesize, categoryid, categoryname);
        Map<String, Object> response = new HashMap<>();
        response.put("records", currentPage.getRecords());
        response.put("total", currentPage.getTotal());
        return Result.ofSuccess(response);
        //return Result.ofSuccess(categoryService.list());
    }

    @GetMapping("/{id}")
    public Result<Categories> getCategoryById(@PathVariable Integer id) {
        Categories categories = new Categories();
        try {
            if (id != null && id > 0) {
                LambdaQueryWrapper<Categories> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Categories::getCategoryid, id);
                categories = categoryService.getOne(queryWrapper);
            }
        } catch (Exception e) {
            return Result.ofFail(CommonErrorCode.INVALID_PARAM);
        }
        return Result.ofSuccess(categories);
    }

    //编辑分类
    @PutMapping("/update")
    public Result<Void> editCategory(@RequestBody Categories categories) {
        try {
            LambdaQueryWrapper<Categories> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Categories::getCategoryid, categories.getCategoryid()).eq(Categories::getCreatetime, categories.getCreatetime());
            Categories one = categoryService.getOne(queryWrapper);
            if (one != null) {
                one.setCategoryname(categories.getCategoryname());
                categoryService.update(one, queryWrapper);
                return Result.ofSuccess();
            }
        } catch (Exception e) {
            return Result.ofFail(CommonErrorCode.INVALID_PARAM);
        }
        return Result.ofFail(CommonErrorCode.FAILURE);
    }

    //删除分类
    @DeleteMapping("/{id}")
    public Result<Void> deleteCategory(@PathVariable Integer id) {
        try {
            //查询分类是否关联文章
            LambdaQueryWrapper<Posts> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Posts::getCategoryid, id);
            List<Posts> list = postService.list(queryWrapper);
            if(list != null && !list.isEmpty()){
                for (int i = 0; i < list.size(); i++) {
                    Posts post = list.get(i);
                    post.setCategoryid(0);
                    postService.updatePostById(post);
                }
            }
            categoryService.removeById(id);
            return Result.ofSuccess();
        } catch (Exception e) {
            return Result.ofFail(CommonErrorCode.FAILURE);
        }
    }

    //添加分类
    @PostMapping("/add")
    public Result<Void> addCategory(@RequestBody Categories categories) {
        try {
            LambdaQueryWrapper<Categories> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Categories::getCategoryname, categories.getCategoryname());
            List<Categories> list = categoryService.list(queryWrapper);
            if(list != null && !list.isEmpty()){
                return Result.ofFail("444", "分类已存在");
            }else{
                categories.setCreatetime(new Date());
                categoryService.save(categories);
                return Result.ofSuccess();
            }
        }catch (Exception e){
            return Result.ofFail(CommonErrorCode.FAILURE);
        }
    }

    //不分页查询全部分类用于下拉框
    @GetMapping("/listAll")
    public Result<List<Categories>> listAllCategory() {
        return Result.ofSuccess(categoryService.list());
    }
}
